package com.aabte.spring.beanpostprocess;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.support.SimpleInstantiationStrategy;

/**
 * 自定义实现Bean后置处理器，参考实现
 * {@link org.springframework.context.support.ApplicationContextAwareProcessor}
 * {@link org.springframework.validation.beanvalidation.BeanValidationPostProcessor}
 *
 * @author Daniel
 */
public class MyBeanPostProcessor implements BeanPostProcessor {
    /**
     * 在Bean实例化后，{@link SimpleInstantiationStrategy#createBeanInstance(String, RootBeanDefinition, Object[])}
     * 并且属性被赋值后 {@link AbstractAutowireCapableBeanFactory#doCreateBean(String, RootBeanDefinition, Object[])}
     * {@link AbstractAutowireCapableBeanFactory#populateBean(String, RootBeanDefinition, BeanWrapper)}
     * 所有初始化方法调用前被调用
     * <p>
     * {@link AbstractAutowireCapableBeanFactory#doCreateBean(String, RootBeanDefinition, Object[])}
     * {@link AbstractAutowireCapableBeanFactory#createBeanInstance(String, RootBeanDefinition, Object[])}
     * {@link AbstractAutowireCapableBeanFactory#populateBean(String, RootBeanDefinition, BeanWrapper)}
     * {@link AbstractAutowireCapableBeanFactory#initializeBean(String, Object, RootBeanDefinition)}
     * {@link AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeInitialization(Object, String)}
     * {@link AbstractAutowireCapableBeanFactory#invokeInitMethods(String, Object, RootBeanDefinition)}
     * {@link AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsAfterInitialization(Object, String)}
     *
     * @return 如果返回null，则后面的后置处理器初始化方法不会被调用
     * {@link AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeInitialization}
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("Invoke MyBeanPostProcessor.postProcessBeforeInitialization method... beanName = " + beanName);
        return bean;
    }

    /**
     * 在Bean实例化后，所有初始化方法调用后被调用
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("Invoke MyBeanPostProcessor.postProcessAfterInitialization method... beanName = " + beanName);
        return bean;
    }
}
